/**
 * Created with JetBrains WebStorm.
 * User: Administrator
 * Date: 5/10/13
 * Time: 10:04 PM
 * To change this template use File | Settings | File Templates.
 */

angular.module("ui.ssnau.powerButton", [])

.directive("powerButton", function(){
		return {
			restrict: "E",
			require: '?ngModel',
			replace: true,
			scope: {
				label: "@label",
				innerModel: "=ngModel"//让isolate scope内部可以引用到外部ngModel的对象
			},
			template: '<div>' +
									'<label class="share-label">{{label}}</label>' +
									'<div class="toggle">' +
											'<label class="toggle-radio">ON</label>' +
											'<label class="toggle-radio">OFF</label>' +
									'</div>' +
								'</div>',
			link: function(scope, element) {
				var toggleNode = $(element[0].children[1]);

				element.on('click', 'label', function(){
					toggleNode.toggleClass("toggle-off");
					var isOn = !toggleNode.hasClass('toggle-off');
					scope.$apply(function() {
						scope.innerModel = isOn;
					});
				});

				//innerModel绑定了外部的ngModel，故在此处watch即可知晓外部变化
				scope.$watch("innerModel", function(newVal){
					render(newVal);
				});

				function render(isOn){
					isOn ? toggleNode.removeClass("toggle-off") : toggleNode.addClass("toggle-off");
				}
			}
		}
});

/**
 * @ngdoc directive
 * @name ui.ssnau.directive.powerButton
 *
 * @element power-button
 *
 * @example
 <doc:example>
 <doc:source>
		<power-button label="WIFI" ng-model="wifiEnable"></power-button>
 </doc:source>
 </doc:example>
 */